package controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import dao.Products;

public class UploadImage extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	protected void doProcess(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (!isMultipart) {
			System.out.println("File Not Uploaded");
		} else {
			HttpSession session = request.getSession();
			String productId = (String) session.getAttribute("product_id");
			
			System.out.println("Product id= === " + productId);
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items = null;

			try {
				items = upload.parseRequest(request);
				System.out.println("items: " + items);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					String name = item.getFieldName();
					System.out.println("name: " + name);
					String value = item.getString();
					System.out.println("value: " + value);
				} else {
					try {
						String itemName = item.getName();
						Random generator = new Random();
						int r = Math.abs(generator.nextInt());

						String reg = "[.*]";
						String replacingtext = "";
						System.out.println("Text before replacing is:-"
								+ itemName);
						Pattern pattern = Pattern.compile(reg);
						Matcher matcher = pattern.matcher(itemName);
						StringBuffer buffer = new StringBuffer();

						while (matcher.find()) {
							matcher.appendReplacement(buffer, replacingtext);
						}
						int IndexOf = itemName.indexOf(".");
						String domainName = itemName.substring(IndexOf);
						System.out.println("domainName: " + domainName);

						String finalimage = buffer.toString() + "_" + r
								+ domainName;
						System.out.println("Final Image===" + finalimage);

						String currentDirectory = getServletContext()
								.getRealPath("");
						String imgPath = currentDirectory + "\\img\\upload\\";
						System.out.println("path===" + imgPath);
						File savedFile = new File(imgPath + finalimage);
						item.write(savedFile);
						out.println("<html>");
						out.println("<body>");
						out.println("<table><tr><td>");
						out.println("<img src='" + request.getContextPath()
								+ "/img/upload/" + finalimage
								+ "' width='100px' height='100px'>");
						out.println("</td></tr></table>");

						String imgUrl = imgPath + finalimage;
						try {
							System.out.println("itemName::::: " + itemName);
							Products productDTO = new Products();
							productDTO.SaveProductImage(productId, finalimage);
							System.out
									.println("Query Executed Successfully++++++++++++++");
							out.println("image inserted successfully");
							out.println("</body>");
							out.println("</html>");
						} catch (Exception e) {
							System.out.println(e.getMessage());
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
